#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>

//定义全局变量要接受或者发送的数据
char name[20];//姓名
char buf[255];//消息  
int clifd;//链接标识
int confdnum[60];//记录
int count = 0;

//该线程发送消息
void* message(void* arg)
{
	int index = *(int *)arg;
	char buf_rcv[255] = {};
	char buf_snd[255] = {};
	//第一次读取用户姓名
	char name[20] = {};
	int ret = recv(confdnum[index],name,sizeof(name),0);
	printf("index:%d\n",index);
	if(0 > ret)
	{
		perror("recv");
		close(confdnum[index]);
	}

	while(1)
	{
		bzero(buf_rcv,sizeof(buf_rcv));
		recv(confdnum[index],buf_rcv,sizeof(buf_rcv),0);

		//判断是否退出
		if(0 == strcmp("quit",buf_rcv))
		{
			sprintf(buf_snd,"%s已经退出悟空聊天室",name);
			for(int i = 0;i <= count;i++)
			{
				if(i == index || 0 == confdnum[i])
				{
					continue;
				}

				send(confdnum[i],buf_snd,strlen(buf_snd),0);
			}
			confdnum[index] = -1;
			pthread_exit(0);
					
		}


		sprintf(buf_snd,"%s:%s",name,buf_rcv);
		printf("%s\n",buf_snd);
		for(int i = 0;i <= count;i++)
		{
			if(i == index || 0 == confdnum[i])
			{
				continue;
			}

			send(confdnum[i],buf_snd,sizeof(buf_snd),0);
		}
		
	}
	
}


//主函数线程负责接受消息
int main(int argc,char* argv[])
{
	if(3 != argc)
	{
		perror("argc");
		return -1;
	}

	printf("悟空聊天室聊天中......\n");

	//创建一个socket对象
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	//创建网络通信对象
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(argv[1]));
	addr.sin_addr.s_addr = inet_addr(argv[2]);

	//绑定对象
	int ret = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(0 > ret)
	{
		perror("bind");
		return -1;
	}

	//设置监听数
	listen(sockfd,50);

	struct sockaddr_in src_addr;
	socklen_t addr_len = sizeof(src_addr);

	//等待多用户链接
	int index = 0;
	while(1)
	{
		if(50 >= count)
		{
			//链接
			confdnum[count] = accept(sockfd,(struct sockaddr*)&src_addr,&addr_len);
			++count;

			index = count-1;
			pthread_t tid = 0;
			int ret1 = pthread_create(&tid,NULL,message,&index);
			if(0 > ret1)
			{
				perror("pthread_creat");
				return -1;
			}
	
		}
	}

}

